package com.author.document.view;

import javax.swing.text.Element;
import javax.swing.text.html.ParagraphView;

public class MultiPageParagraphView extends ParagraphView implements
		MultiPageView {
	private int	pageOffset		= 0;
	private int	breakSpan		= 0;

	private int	startPageNumber	= 0;
	private int	endPageNumber	= 0;

	private int	extraSpace		= 0;

	public MultiPageParagraphView(Element elem) {
		super(elem);
	}

	public void layout(int width, int height) {
		super.layout(width, height);
	}

	@Override
	public int getPageOffset() {
		return this.pageOffset;
	}

	@Override
	public int getBreakSpan() {
		return this.breakSpan;
	}

	@Override
	public int getStartPageNumber() {
		return this.startPageNumber;
	}

	public int getEndPageNumber() {
		return this.endPageNumber;
	}

	@Override
	public int getAdditionalSpace() {
		return this.extraSpace;
	}

	@Override
	public void setPageOffSet(int offset) {
		this.pageOffset = offset;
	}

	@Override
	public void setBreakSpan(int span) {
		this.breakSpan = span;
	}

	@Override
	public void setStartPageNumber(int pageNumber) {
		this.startPageNumber = pageNumber;
	}

	@Override
	public void setEndPageNumber(int pageNumber) {
		this.endPageNumber = pageNumber;
	}

	public void setAdditionalSpace(int space) {
		this.extraSpace += space;
	}

	@Override
	protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets,
			int[] spans) {
		super.layoutMajorAxis(targetSpan, axis, offsets, spans);
		multiPageLayout(targetSpan, axis, offsets, spans);
	}

	@Override
	public void multiPageLayout(int targetSpan, int axis, int[] offsets,
			int[] spans) {
		if (breakSpan == 0) {
			return;
		}

		int space = breakSpan;
		int n = offsets.length;

		/* Reset space calculation */
		this.setAdditionalSpace(-this.getAdditionalSpace());

		for (int i = 0; i < n; i++) {
			if ((offsets[i] + spans[i]) > space) {
				int startPageNumber = this.getStartPageNumber();
				int endPageNumber = startPageNumber + 1;
				this.setEndPageNumber(endPageNumber);

				int newspan = (endPageNumber * PageConstants.PAGE_HEIGHT)
						- (startPageNumber * PageConstants.PAGE_HEIGHT)
						- spans[i];
				space = newspan;

				/* Add additional space */
				int addspace = (endPageNumber * PageConstants.PAGE_HEIGHT)
						- (startPageNumber * PageConstants.PAGE_HEIGHT)
						- pageOffset - offsets[i];
				addspace += (endPageNumber * (PageConstants.PAGE_BOTTOM_INSET + PageConstants.PAGE_TOP_INSET));
				this.setAdditionalSpace(addspace);

				for (int j = i; j < n; j++) {
					offsets[j] += addspace;
				}
			}
		}
	}

}
